<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Controllers;

use Carbon\Carbon;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;

/**
 * 验证码模块
 *
 * Class CaptchaController
 * @package App\Http\Controllers
 */
class CaptchaController extends Controller
{
    /**
     * 获取验证码
     * @return \Illuminate\Http\JsonResponse
     */
    public function img()
    {
        $phrase = new PhraseBuilder;
        // 设置验证码位数
        $code = $phrase->build(4);
        // 生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder($code, $phrase);
        // 设置背景颜色25,25,112
        $builder->setBackgroundColor(212, 202, 247);
        // 设置倾斜角度
        $builder->setMaxAngle(25);
        // 设置验证码后面最大行数
        $builder->setMaxBehindLines(10);
        // 设置验证码前面最大行数
        $builder->setMaxFrontLines(10);
        // 设置验证码颜色
        $builder->setTextColor(131, 145, 158);
        // 可以设置图片宽高及字体
        $builder->build($width = 150, $height = 40, $font = null);
        // 获取验证码的内容
        $phrase = $builder->getPhrase();

        // 缓存验证码周期：30秒后过期
        $captcha_id = md5(rand(1, 1000) . time());
        \Cache::put($captcha_id, $phrase, Carbon::now()->addMinutes(1));

        // 返回验证码信息
        $data = [
            'captcha_id' => $captcha_id,
            'img' => $builder->inline(),
        ];
        return $this->success('', $data);
    }
}
